<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="search_form.backupName" placeholder="备份名称" style="width: 200px;" clearable />
     
      <el-button type="primary" icon="el-icon-search" @click="handle_search">搜索</el-button>
      <el-button @click="handle_reset">重置</el-button>
      <el-button type="success" icon="el-icon-document-add" @click="handle_backup">立即备份</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="backup_list"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="备份ID" />
    <el-table-column prop="backupName" label="备份名称" />
      <el-table-column prop="backupPath" label="备份路径" />
      <el-table-column prop="backupSize" label="文件大小" />
      <el-table-column prop="created" label="备份时间" />
      <el-table-column prop="backupType" label="备份类型">
        <template slot-scope="scope">
          <el-tag :type="scope.row.backupType === 1 ? 'success' : 'info'">
            {{ scope.row.backupType === 1 ? '全量备份' : '增量备份' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="creatorId" label="创建者ID" />
      <el-table-column label="操作" width="250">
        <template slot-scope="scope" >
          <el-button type="primary" size="small" @click="download_backup(scope.row)">下载</el-button>
          <el-button type="warning" size="small" @click="handle_restore(scope.row)">恢复</el-button>
          <el-button type="danger" size="small" @click="handle_delete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="page_size"
        :current-page="page_num"
        @current-change="handle_current_change"
        @size-change="handle_size_change"
      />
    </div>

    <!-- 备份配置对话框 -->
    <el-dialog
      title="备份配置"
      :visible.sync="backup_dialog_visible"
      width="400px"
    >
      <el-form
        :model="backup_form"
        ref="backup_form"
        label-width="100px"
      >
        <el-form-item label="备份名称" prop="backupName">
          <el-input v-model.trim="backup_form.backupName" placeholder="请输入备份名称" />
        </el-form-item>
        <el-form-item label="备份类型" prop="backupType">
          <el-radio-group v-model="backup_form.backupType">
            <el-radio :label="1">全量备份</el-radio>
            <el-radio :label="2">增量备份</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backup_dialog_visible = false">取消</el-button>
        <el-button type="primary" @click="confirm_backup">确认备份</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sysBackupApi from '@/api/sys-backup'

export default {
  name: 'BackupManagement',
  data() {
    return {
      loading: false,
      backup_list: [],
      total: 0,
      page_num: 1,
      page_size: 10,
      date_range: [],
      search_form: {
        backupName: ''
      },
      backup_dialog_visible: false,
      backup_form: {
        backupName: '',
        backupType: 1
      }
    }
  },
  created() {
    this.get_list()
  },
  methods: {
    // 获取备份列表
    async get_list() {
      this.loading = true
      try {
        const params = {
          page_num: this.page_num,
          page_size: this.page_size,
          ...this.search_form
        }
        
        // 添加日期范围
        if (this.date_range && this.date_range.length === 2) {
          params.start_time = this.date_range[0]
          params.end_time = this.date_range[1]
        }
        
        const { data } = await sysBackupApi.list(params)
        this.backup_list = data.records
        this.total = data.total
      } catch (error) {
        this.$message.error('获取备份列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handle_search() {
      this.page_num = 1
      this.get_list()
    },
    // 重置搜索条件
    handle_reset() {
      this.search_form = {
        backupName: ''
      };
      this.get_list();
    },
    
    // 立即备份
    handle_backup() {
      // 生成默认备份名称（当前时间）
      const now = new Date()
      const defaultName = `backup_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`
      this.backup_form = {
          backupName: defaultName,
          backupType: 1
        }
      this.backup_dialog_visible = true
    },
    
    // 确认备份
    async confirm_backup() {
      try {
        await sysBackupApi.add(this.backup_form)
        this.$message.success('备份任务已启动')
        this.backup_dialog_visible = false
        this.get_list()
      } catch (error) {
        this.$message.error('备份失败')
      }
    },
    
    // 下载备份
    async download_backup(row) {
        try {
          // 使用axios发送带token的GET请求，设置responseType为blob
          const response = await this.$axios({
            url: `/sys-backup/download/${row.id}`,
            method: 'get',
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/octet-stream'
            }
          })
         
          
          // 创建下载链接并触发下载
          const blob = new Blob([response.data])
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = row.backupName || `backup_${row.id}.zip`
          document.body.appendChild(link)
          link.click()
          
          // 清理
          setTimeout(() => {
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          }, 100)
        } catch (error) {
          this.$message.error('下载失败')
        }
      },
    
    // 恢复备份
    async handle_restore(row) {
      this.$confirm('确定要恢复此备份吗？恢复过程可能需要一些时间，请勿关闭页面！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await sysBackupApi.restore(row.id)
          this.$message.success('恢复成功')
        } catch (error) {
          this.$message.error('恢复失败')
        }
      })
    },
    
    // 删除备份
    async handle_delete(id) {
      this.$confirm('确定要删除此备份吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await sysBackupApi.delete(id)
          this.$message.success('删除成功')
          this.get_list()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    
    // 分页处理
    handle_current_change(val) {
      this.page_num = val
      this.get_list()
    },
    
    handle_size_change(val) {
      this.page_size = val
      this.page_num = 1
      this.get_list()
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>